﻿/*
 * Copyright (c) Martin Kinkelin
 *
 * See the "License.txt" file in the root directory for infos
 * about permitted and prohibited uses of this code.
 */

using System;
using System.Windows.Forms;

namespace Jarf
{
	/// <summary>
	/// Starts and displays a Windows shutdown timer.
	/// </summary>
	public partial class ShutdownDialog : BaseForm
	{
		private ShutdownType _type;
		private int _timeOut;

		private string _formatString;



		public ShutdownDialog(ShutdownType type, int timeOutSeconds)
		{
			InitializeComponent();

			if (!WindowsShutdownManager.AcquireShutdownPrivilege())
				throw new InvalidOperationException("The process has no shutdown privilege.");

			_type = type;
			_timeOut = timeOutSeconds;

			switch (type)
			{
				case ShutdownType.LogOff:
					_formatString = "The current user is going to be logged off in: {0}";
					break;
				case ShutdownType.PowerOff:
					_formatString = "The system is going to be shut down in: {0}";
					break;
				case ShutdownType.Reboot:
					_formatString = "The system is going to be rebooted in: {0}";
					break;
				case ShutdownType.Suspend:
					_formatString = "The system is going to switch to stand-by mode in: {0}";
					break;
				case ShutdownType.Hibernate:
					_formatString = "The system is going to hibernate in: {0}";
					break;
			}

			label1.Text = string.Format(_formatString, _timeOut);
		}


		private void timer1_Tick(object sender, EventArgs e)
		{
			--_timeOut;

			if (_timeOut > 0)
			{
				label1.Text = string.Format(_formatString, _timeOut);
				return;
			}

			timer1.Stop();

			DialogResult = DialogResult.OK;

			Close();
		}

		private void ShutdownDialog_Load(object sender, EventArgs e)
		{
			timer1.Start();
		}

		private void ShutdownDialog_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (DialogResult == DialogResult.OK)
				WindowsShutdownManager.Shutdown(_type, true, true);
		}
	}
}
